import React, { useState, useRef } from "react";

import { useNavigate, useParams } from "react-router-dom";
import { Button, Table, Space, Form, Input, Popconfirm, Select } from "antd";
import {
  DeleteOutlined,
  PlusOutlined,
  SearchOutlined,
  SyncOutlined,
  CloseOutlined,
  DownOutlined,
  ReloadOutlined,
} from "@ant-design/icons";
import TableLayout, {
  SearchContainer,
  SearchAction,
  SearchForm,
  OperateContainer,
  MainContainer,
} from "@/components/templates/TableLayout";
import { ButtonCollapsed } from "@/components/iteration";
import { SelectUnAuthUser } from "@/pages/system/user/components";
import { AuthButton } from "@/components/auth";
import { useLoadPageData } from "@/hooks";
import PropTypes from "prop-types";

import { getAuthedUserList, addAuthUsers, cancelAuthUser } from "@/api/system/role";

const AUTH_PERMISSION = {
  ADD: "system:role:auth:add",
  CANCEL: "system:role:auth:cancel",
};

const HeaderComponent = ({ onSearch, onReset }) => {
  const [folded, setFolded] = useState(false);
  const [searchType, setSearchType] = useState("keyword");
  const inputRef = useRef(null);

  const onFinish = (values) => {
    const data = Object.entries(values).filter(([_, value]) => !!value);
    data.length && onSearch(Object.fromEntries(data));
  };

  const hanldeSearch = () => {
    const value = inputRef.current.input.value;
    value && onSearch({ [searchType]: value });
  };

  const options = [
    { label: "综合搜索", value: "keyword", placeholder: "综合搜索" },
    { label: "用户名称", value: "userName", placeholder: "请输入用户名称" },
    { label: "手机号码", value: "goodsName", placeholder: "请输入手机号码" },
  ];

  return (
    <SearchContainer>
      <SearchAction>
        <Space.Compact>
          <Select
            defaultValue={searchType}
            style={{ width: 120 }}
            options={options}
            onChange={(v) => setSearchType(v)}
          />
          <Input ref={inputRef} placeholder={options.find((item) => item.value === searchType).placeholder} />
          <Button icon={<SearchOutlined />} onClick={hanldeSearch} />
        </Space.Compact>

        <ButtonCollapsed
          type="link"
          icon={<DownOutlined />}
          iconPosition="end"
          collapsed={folded}
          onClick={() => setFolded(!folded)}
        >
          高级搜索
        </ButtonCollapsed>
      </SearchAction>
      <SearchForm collapse={folded}>
        <Form className="search-card" layout="inline" autoComplete="off" onFinish={onFinish} onReset={onReset}>
          <Form.Item name="userName" label="用户名称">
            <Input placeholder="请输入用户名称" />
          </Form.Item>
          <Form.Item name="phoneNumber" label="手机号">
            <Input placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                搜索
              </Button>
              <Button icon={<SyncOutlined />} htmlType="reset">
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </SearchForm>
    </SearchContainer>
  );
};
HeaderComponent.propTypes = {
  onSearch: PropTypes.func,
  onReset: PropTypes.func,
};

const OperateCompoent = ({ deleteDisabled, onAddAuth, onCancelAuth, onRefresh }) => {
  const navigate = useNavigate();

  return (
    <OperateContainer>
      <Space>
        <AuthButton auth={AUTH_PERMISSION.ADD} type="primary" ghost icon={<PlusOutlined />} onClick={onAddAuth}>
          添加
        </AuthButton>

        <Popconfirm
          title="系统提示"
          description="是否确认删除多项用户的数据项？"
          onConfirm={() => onCancelAuth}
          okText="是"
          cancelText="否"
        >
          <AuthButton auth={AUTH_PERMISSION.CANCEL} danger ghost icon={<DeleteOutlined />} disabled={deleteDisabled}>
            取消
          </AuthButton>
        </Popconfirm>
      </Space>
      <Space>
        <Button icon={<ReloadOutlined />} onClick={onRefresh} />
        <Button icon={<CloseOutlined />} onClick={() => navigate(-1)} />
      </Space>
    </OperateContainer>
  );
};
OperateCompoent.propTypes = {
  deleteDisabled: PropTypes.bool,
  onAddAuth: PropTypes.func,
  onCancelAuth: PropTypes.func,
  onRefresh: PropTypes.func,
};

const TableComponent = ({ onCancelAuth, ...resProps }) => {
  const columns = [
    { key: "userName", title: "用户名", dataIndex: "userName" },
    { key: "nickName", title: "用户昵称", dataIndex: "nickName" },
    { key: "phoneNumber", title: "手机号码", dataIndex: "phoneNumber" },
    { key: "createTime", title: "创建时间", dataIndex: "createTime" },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space>
          <Popconfirm
            title="系统提示"
            description={`是否确认取消授权？`}
            onConfirm={() => onCancelAuth(record.userId)}
            okText="是"
            cancelText="否"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              取消授权
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <MainContainer>
      <Table size="middle" {...resProps} columns={columns} />
    </MainContainer>
  );
};
TableComponent.propTypes = {
  onCancelAuth: PropTypes.func,
  resProps: PropTypes.object,
};

const GeneralComponent = () => {
  const { id: roleId } = useParams();
  const {
    loading,
    dataSource,
    pagination,
    onSearchData, // 搜索数据
    onRefreshData,
    onResetData,
    onPageChange,
  } = useLoadPageData(getAuthedUserList, { roleId });
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const onAddAuthUsers = async (values) => {
    await addAuthUsers(roleId, values);
    onRefreshData();
  };

  const onCancelAuth = async (value) => {
    await cancelAuthUser(roleId, [value]);
    setSelectedRowKeys(selectedRowKeys.filter((item) => item !== value));
    onRefreshData();
  };

  const onBatchCancelAuth = async () => {
    if (!selectedRowKeys.length) return;
    await cancelAuthUser(roleId, selectedRowKeys);
    onRefreshData();
    setSelectedRowKeys([]);
  };

  return (
    <TableLayout>
      {modalVisible && (
        <SelectUnAuthUser open={modalVisible} onCallback={onAddAuthUsers} onCancel={() => setModalVisible(false)} />
      )}

      <HeaderComponent onSearch={onSearchData} onReset={onResetData} />
      <OperateCompoent
        onAddAuth={() => setModalVisible(true)}
        onCancelAuth={onBatchCancelAuth}
        isDeleteDisabled={!selectedRowKeys.length}
        onRefresh={onRefreshData}
      />
      <TableComponent
        dataSource={dataSource}
        loading={loading}
        rowSelection={{
          selectedRowKeys,
          getCheckboxProps: ({ admin }) => ({ disabled: admin }),
          onChange: (v) => setSelectedRowKeys(v),
        }}
        pagination={{
          current: pagination.pageNum,
          pageSize: pagination.pageSize,
          total: pagination.totalPages,
          showSizeChanger: true,
          showTotal: (total) => `共${total}条`,
          onChange: onPageChange,
        }}
        onCancelAuth={onCancelAuth}
      />
    </TableLayout>
  );
};

export default GeneralComponent;
